﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace DayuSms {
	public class SmsSender {
		private static ITopClient _client;

		private static ITopClient Client => _client ??
									(_client =
										new DefaultTopClient("https://eco.taobao.com/router/rest", "23354508", "88fdc0d6d4c4e51314cd524526859fbb"));

		//https://api.alidayu.com/doc2/apiDetail?spm=a3142.7802526.1.19.pTaeWk&apiId=25450
		public bool SendCode(string Tel, string Code, out string msg) {
			var req = new AlibabaAliqinFcSmsNumSendRequest {
				SmsType = "normal",
				SmsFreeSignName = "卡门",
				SmsParam = $"{{\"code\":\"{Code}\",\"product\":\"卡门\"}}",
				RecNum = Tel,
				SmsTemplateCode = "SMS_8290163"
			};
			var rsp = Client.Execute(req);
			msg = rsp.Body;
			return (!rsp.IsError);
		}

		static string getSmsParam(IDictionary<string, object> values) {
			if (values.Count == 0) return string.Empty;
			var sb = new StringBuilder();
			foreach (var item in values) {
				sb.AppendFormat(",\"{0}\":\"{1}\"", item.Key, item.Value);
			}
			return $"{{{sb.Remove(0, 1)}}}";
		}

		public bool Send(string SmsTemplateCode, string Tel, IDictionary<string, object> values, out string msg) {
			var req = new AlibabaAliqinFcSmsNumSendRequest {
				SmsType = "normal",
				SmsFreeSignName = "卡门",
				SmsParam = getSmsParam(values),
				RecNum = Tel,
				SmsTemplateCode = SmsTemplateCode
			};
			var rsp = Client.Execute(req);
			msg = rsp.Body;
			return (!rsp.IsError);
		}
	}
}
